export default function (isLoading = true, delay = 100) {
  // 逻辑说明： isLoading为true时，添加loading元素，isLoading为false且delay时间内没有再次开启loading，则移除loading元素
  let timer = null
  if (isLoading) {
    // 如果已经存在loading元素，则不重复添加
    const existingLoading = document.querySelector('.system-loading-box')
    if (!existingLoading) {
      clearTimeout(timer)
      addLoadingElement()
    }
  } else {
    // 延迟移除loading元素
    clearTimeout(timer)
    timer = setTimeout(() => {
      removeLoadingElement()
    }, delay)
  }
}
// 添加loading元素
const addLoadingElement = () => {
  const fragment = new DocumentFragment()
  const loadingDom = document.createElement('div')
  loadingDom.setAttribute('class', 'system-loading-box')
  const spinSpan = document.createElement('span')
  spinSpan.setAttribute('class', 'dot dot-spin')
  for (let i = 0; i < 4; i++) {
    const liDom = document.createElement('i')
    spinSpan.appendChild(liDom)
  }
  loadingDom.appendChild(spinSpan)
  fragment.appendChild(loadingDom)
  document.body.appendChild(fragment)
}
// 移除loading元素
const removeLoadingElement = () => {
  const loadingDom = document.querySelector('.system-loading-box')
  if (loadingDom) {
    document.body.removeChild(loadingDom)
  }
}
